package com.zweirm.lagee_quizing.controller;

import com.zweirm.lagee_quizing.domain.Clazz;
import com.zweirm.lagee_quizing.domain.Paper;
import com.zweirm.lagee_quizing.domain.Quiz;
import com.zweirm.lagee_quizing.service.PaperService;
import com.zweirm.lagee_quizing.service.QuizService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
public class QuizController {
    @Autowired
    private QuizService quizService;

    @Autowired
    private PaperService paperService;

    @RequestMapping("/quiz")
    public String findAllQuiz(Model model) {
        List<Quiz> quizzes = quizService.findAllQuiz("1");
        model.addAttribute("quizzes", quizzes);
        return "forward:/goQuiz";
    }

    @RequestMapping("/saveQuiz")
    public String saveQuiz(String title, String type, String[] clazz, String paper) {
        quizService.saveQuiz(title, type, clazz, paper);
        return "redirect:/quiz";
    }

    @RequestMapping("/quizDetails/{quizId}")
    public String quizDetails(@PathVariable Long quizId, Model model) {
        Quiz quiz = quizService.quizDetails(quizId);
        List<Paper> papers = paperService.showAll("1");

        List<Clazz> clazzes = quiz.getClazzes();
        List<String> clazzNames = new ArrayList<>();
        for (Clazz clazz : clazzes) {
            clazzNames.add(clazz.getName());
        }
        Paper paper = quiz.getPaper();

        model.addAttribute("title", quiz.getTitle());
        model.addAttribute("type", quiz.getType());
        model.addAttribute("clazz", clazzNames);
        model.addAttribute("destPaper", paper.getName());
        model.addAttribute("papers", papers);
        model.addAttribute("quizId", quizId);
        return "/quiz_details";
    }

    @RequestMapping("/updateQuiz")
    public String quizUpdate(String title,
                             String type,
                             String[] clazz,
                             String paper,
                             Long quizId,
                             Model model) {
        quizService.quizUpdate(title, type, clazz, paper, quizId);
        quizDetails(quizId, model);
        return "forward:/quizDetails/" + quizId;
    }

    @RequestMapping("/quizDelete/{quizId}")
    public String deleteQuiz(@PathVariable Long quizId) {
        quizService.deleteQuiz(quizId);
        return "redirect:/quiz";
    }
}
